<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>员工管理页面</title>
    <link rel="stylesheet" href="layui/css/layui.css">
</head>
<body>

<table class="layui-hide" id="demo" lay-filter="test"></table>
<!--添加或修改员工 弹出框-开始-->
<div id="addOrUpdateDiv" style="display: none;padding-top: 30px">
    <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
        <input type="hidden" name="empId" class="layui-input">

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">姓名</label>
                <div class="layui-input-inline">
                    <input type="text" name="empName" lay-verify="required" autocomplete="off" class="layui-input">
                </div>
            </div>

            <div class="layui-inline">
                <label class="layui-form-label">性别</label>
                <div class="layui-input-inline">
                    <input type="radio" name="gender" value="男" title="男" checked="">
                    <input type="radio" name="gender" value="女" title="女">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">部门</label>

                <div class="layui-input-inline">
                    <select name="deptId" lay-filter="required" lay-search="" lay-verify="required" id="depts">
                        <option value=""></option>

                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label">邮箱</label>
                <div class="layui-input-inline">
                    <input type="text" name="email" lay-verify="required|email" autocomplete="off" class="layui-input">
                </div>
            </div>

        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button type="button" class="layui-btn" lay-submit="" lay-filter="submit">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</div>
<!--添加或修改员工 弹出框-结束-->

<script type="text/html" id="toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="insertEmp">新增员工</button>
    <button class="layui-btn layui-btn-sm" lay-event="batchDelete">批量删除</button>
 </script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>


<script src="layui/layui.js" charset="utf-8"></script>
 <script>
    layui.use(['table','jquery','form','element'], function(){
        var table = layui.table;
        var $=layui.jquery;
        var form=layui.form;
        var element=layui.element;
        var submitType;
        var submitUrl;

        var tableIns=table.render({
            elem: '#demo'
            ,url:'/springboot_mybatisplus/api/selectList'
            ,toolbar: '#toolbarDemo' //开启头部工具栏，并为其绑定左侧模板
            ,title: '用户数据表'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'empId', title:'#',  width:100, fixed: true}
                ,{field:'empName', title:'姓名', edit: 'text'}
                ,{field:'gender', title:'性别', width:100,edit: 'text'}
                ,{field:'email', title:'邮箱', edit: 'text'}
                ,{field:'dept', title:'部门名称', edit: 'text',templet: function(res){
                        return '<em>'+ res.dept.deptName +'</em>'
                    }}
                 ,{fixed: 'right', title:'操作', align: 'center', toolbar: '#barDemo', width:200}
            ]]
            ,page: true
        });

        //头工具栏事件
        table.on('toolbar(test)', function(obj){
            var checkStatus = table.checkStatus('demo'); //获取选中行状态
             switch(obj.event){
                case 'insertEmp':

                     //弹出新增框
                    addDiv=layer.open({
                        type:1,
                        title:'添加',
                        area:['380px', '340px'],
                        content:$('#addOrUpdateDiv'),
                        success:function () {
                            makeSelect();
                            //清空表单
                            $('#dataFrm')[0].reset();
                            submitType='post';
                            submitUrl='/springboot_mybatisplus/api/insert';
                        }
                    })

                    break;

                case 'batchDelete':
                    //批量删除

                    console.log('checkStatus:' + checkStatus.data);
                    var empIds = '';
                    for (var i = 0; i < checkStatus.data.length; i++) {
                        empIds += checkStatus.data[i].empId + ',';
                    }
                    empIds = empIds.substring(0, empIds.lastIndexOf(','));//处理id集合的最后一个-符号
                     if (checkStatus.data.length > 0) {
                        layer.confirm('真的删除所选员工么', function (index) {

                            layer.close(index);
                            //向服务端发送删除指令
                            $.ajax({
                                type: 'DELETE',
                                data: {"id":empIds},
                                url: '/springboot_mybatisplus/api/deleteOneOrBatch',
                                success: function (resp) {
                                    layer.msg(resp.data)
                                    tableIns.reload();
                                }
                            })

                        });
                    } else {
                        layer.msg('至少选择一个员工')
                    }

                    break;

            };
        });

        var currentDeptId;
        //监听行工具事件
        table.on('tool(test)', function(obj){
            var data = obj.data;
            //console.log(obj)
            if(obj.event === 'del'){
                 layer.confirm('真的删除行么', function(index){

                    $.ajax({
                        type: 'DELETE',
                        data: {"id":data.empId},
                        url: '/springboot_mybatisplus/api/deleteOneOrBatch',
                        success:function (resp) {
                            layer.msg(resp.data);
                        }
                    })

                     obj.del();
                    layer.close(index);
                });
            } else if(obj.event === 'edit'){
                //弹出新增框
                addDiv=layer.open({
                    type:1,
                    title:'编辑',
                    area:['380px', '340px'],
                    content:$('#addOrUpdateDiv'),
                    success:function () {
                        form.val("dataFrm",data);

                        //将当前的部门id存起来
                        currentDeptId=data.deptId;
                        makeSelect();
                        submitType='put';
                        submitUrl='/springboot_mybatisplus/api/updateById';
                    }
                })

            }
        });

        //处理下拉框数据
        function makeSelect(){
            $.get('/springboot_mybatisplus/api/selectDeptList',function (res) {
                var depts=$('#depts');
                // alert(depts.html())

                var deptInfo=res.data;
                console.log("res："+res);

                //遍历前先清空
                depts.empty();
                //遍历所有部门，渲染下拉框
                $(deptInfo).each(function (index,element) {
                    // alert(element.deptId+"--"+element.deptName);

                    if(index==0){
                        depts.append("<option value=''></option>");
                    }
                    //如果当前部门的id==正在遍历的部门id，就给下拉增加selected属性
                    if(currentDeptId==element.deptId){
                        depts.append("<option selected='selected' value="+element.deptId+">"+element.deptName+"</option>");
                    }else{
                        depts.append("<option value="+element.deptId+">"+element.deptName+"</option>");
                    }

                    console.log("下拉列表---------"+deptInfo);
                    form.render('select');
                    // alert(depts.html())
                })

            })
        }

        //提交新增或编辑表单
        form.on("submit(submit)",function (obj) {
            //序列化表单数据
            var params=$("#dataFrm").serialize();

            if(submitType=='post') {
                //发送新增请求
                $.post(submitUrl, params, function (resp) {
                    layer.msg(resp.data);
                    layer.close(addDiv);
                    tableIns.reload();
                })
            }
            else if(submitType=='put'){
                //发送修改请求
                $.ajax({
                    url:submitUrl,
                    type:'put',
                    data:params,
                    success:function (resp) {

                        layer.msg(resp.data);
                        layer.close(addDiv);
                        tableIns.reload();

                    }
                })

            }

        })
    });
</script>
</body>
</html>